import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ShowService implements Loggable {
    private List<Show> showList = new ArrayList<>();
    private static final String SHOW_FILE = "shows.txt"; // 存储场次数据的文件
    private List<Hall> halls;
    private MovieService movieService;
    private int showIdCounter = 1;

    // 构造方法：初始化时从文件加载场次数据
    public ShowService(List<Hall> halls, MovieService movieService) {
        this.halls = halls;
        this.movieService = movieService;
        showList = FileUtil.readShowsFromFile(SHOW_FILE, movieService.getAllMovies(), halls);
        // 如果文件为空，自动排片
        if (showList.isEmpty()) {
            autoArrangeShows();
            saveShows(); // 保存到文件
        } else {
            // 从现有场次ID计算计数器初始值
            for (Show show : showList) {
                try {
                    int id = Integer.parseInt(show.getShowId().substring(1));
                    if (id >= showIdCounter) showIdCounter = id + 1;
                } catch (Exception e) {
                    // 忽略格式异常，使用默认计数器
                }
            }
        }
    }

    // 自动排片（为每个影片在每个放映厅排3场）
    public void autoArrangeShows() {
        List<Movie> movies = movieService.getAllMovies();
        LocalDateTime baseTime = LocalDateTime.now().plusHours(2); // 从2小时后开始排片

        for (Movie movie : movies) {
            for (Hall hall : halls) {
                // 每天排3场：10:00、15:00、19:00
                for (int hour : new int[]{10, 15, 19}) {
                    LocalDateTime showTime = baseTime.withHour(hour).withMinute(0);
                    // 高分影片票价更高
                    double price = movie.getScore() > 8.0 ? 60.0 : 45.0;

                    Show show = new Show(
                            "S" + String.format("%03d", showIdCounter++),
                            movie,
                            hall,
                            showTime,
                            price
                    );
                    showList.add(show);
                }
            }
        }
        logOperation("自动排片完成，共" + showList.size() + "场");
    }

    // 获取所有场次
    public List<Show> getAllShows() {
        return new ArrayList<>(showList); // 返回副本，避免外部修改
    }

    // 保存场次数据到文件
    public void saveShows() {
        FileUtil.writeShowsToFile(showList, SHOW_FILE);
    }
}
    